﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models.Response;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;

namespace IOA.MES.Client.Settings
{
    /// <summary>
    /// SettingsIndex.xaml 的交互逻辑
    /// </summary>
    public partial class SettingsIndex : Window
    {
        private List<KeyValuePair<int, string>> machineTypes = new List<KeyValuePair<int, string>>();
        private List<SimpleMachine> machines = new List<SimpleMachine>();
        private List<Workshop> workshops = new List<Workshop>();
        public SettingsIndex()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtApiRoot.Text = BaseEnv.GetStorage("ApiRoot") ?? string.Empty;

            if (!string.IsNullOrWhiteSpace(txtApiRoot.Text))
            {
                btnCheck_Click(null, null);
            }
        }

        private void btnCheck_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtApiRoot.Text))
            {
                return;
            }
            BaseEnv.ApiRoot = txtApiRoot.Text;

            var response = BaseEnv.InvokeApi<QueryMachineTypesResponse>("/api/Common/QueryMachineTypes", new
            {
                WorkshopCode = string.Empty
            });
            if (response.ErrCode != 200)
            {
                CommonMessage.Alert(this, response.ErrMsg);
                return;
            }
            else if (!response.Data.MachineTypes.Any())
            {
                CommonMessage.Alert(this, "获取设备类型列表为空");
                return;
            }

            machineTypes = response.Data.MachineTypes;
            machines = response.Data.Machines;
            workshops = response.Data.Workshops;

            cbWorkshops.ItemsSource = workshops;
            cbWorkshops.DisplayMemberPath = "WorkshopName";
            cbWorkshops.SelectedValuePath = "WorkshopCode";
            var workshopCode = BaseEnv.GetStorage("WorkshopCode") ?? string.Empty;
            var curWorkshop = string.IsNullOrWhiteSpace(workshopCode) ? null : workshops.FirstOrDefault(_ => string.Equals(_.WorkshopCode, workshopCode, StringComparison.CurrentCultureIgnoreCase));
            cbWorkshops.SelectedIndex = curWorkshop == null ? 0 : workshops.IndexOf(curWorkshop);

            cbMachineTypes.ItemsSource = machineTypes;
            cbMachineTypes.DisplayMemberPath = "Value";
            cbMachineTypes.SelectedValuePath = "Key";

            int machineType = -1;
            int.TryParse(BaseEnv.GetStorage("MachineType"), out machineType);

            if (!response.Data.MachineTypes.Any(_ => _.Key == machineType))
            {
                cbMachineTypes.SelectedIndex = 0;
            }
            else
            {
                cbMachineTypes.SelectedIndex = response.Data.MachineTypes.FindIndex(_ => _.Key == machineType);
            }

            CommonMessage.Alert(this, "接口地址校验成功");
        }

        private void cbWorkshops_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            RenderMachines();
        }

        private void cbMachineTypes_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            RenderMachines();
        }

        private void RenderMachines()
        {
            var workshopCode = cbWorkshops.SelectedValue == null ? string.Empty : Convert.ToString(cbWorkshops.SelectedValue);
            var machineType = cbMachineTypes.SelectedValue == null ? 0 : Convert.ToInt32(cbMachineTypes.SelectedValue);
            if (string.IsNullOrWhiteSpace(workshopCode) || machineType <= 0)
            {
                return;
            }

            var curMachines = machines.Where(_ => string.Equals(workshopCode, _.WorkshopCode, StringComparison.CurrentCultureIgnoreCase)
                                                  && _.MachineType == machineType).ToList();
            if (new List<int> { (int)MachineType.WeldingMachine, (int)MachineType.TopMachine }.Contains(Convert.ToInt32(cbMachineTypes.SelectedValue)))
            {
                curMachines.Insert(0, new SimpleMachine
                {
                    MachineId = 0,
                    MachineName = "",
                    MachineType = Convert.ToInt32(cbMachineTypes.SelectedValue)
                });
            }
            cbMachines.ItemsSource = null;
            cbMachines.ItemsSource = curMachines;
            cbMachines.DisplayMemberPath = "MachineName";
            cbMachines.SelectedValuePath = "MachineId";

            var machineIdCode = BaseEnv.GetStorage("MachineId");
            if (!string.IsNullOrWhiteSpace(machineIdCode) && curMachines.Any(_ => _.MachineId == Convert.ToInt32(machineIdCode)))
            {
                cbMachines.SelectedValue = Convert.ToInt32(machineIdCode);
            }
            else
            {
                cbMachines.SelectedIndex = 0;
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            var workshopCode = Convert.ToString(cbWorkshops.SelectedValue).Trim();
            var machineType = machineTypes[cbMachineTypes.SelectedIndex].Key;
            var apiRoot = txtApiRoot.Text.Trim();
            var machineId = Convert.ToInt32(cbMachines.SelectedValue);
            var machineName = ((SimpleMachine)cbMachines.SelectedItem).MachineName;
            if (string.IsNullOrWhiteSpace(workshopCode) || machineType < 0 || string.IsNullOrWhiteSpace(apiRoot))
            {
                return;
            }

            BaseEnv.SetStorage("WorkshopCode", workshopCode);
            BaseEnv.SetStorage("MachineType", machineType.ToString());
            BaseEnv.SetStorage("ApiRoot", apiRoot);
            BaseEnv.SetStorage("MachineId", machineId.ToString());
            BaseEnv.SetStorage("MachineName", machineName);

            BaseEnv.ApiRoot = apiRoot;
            BaseEnv.WorkshopCode = workshopCode;
            BaseEnv.MachineType = machineType;
            BaseEnv.MachineId = machineId;
            BaseEnv.machineName = machineName;

            CommonMessage.Log(LogLevel.Warn, $"修改参数：ApiRoot：{apiRoot}，WorkshopCode：{workshopCode}，MachineType：{machineType}，machineName：{machineName}");

            this.DialogResult = true;
            this.Close();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (this.DialogResult == true)
            {
                Environment.Exit(0);
            }
        }
    }
}
